<script setup lang="ts">
import { ref, reactive, computed, watchEffect, onMounted } from 'vue';
import deviceList from './data/deviceList.ts';
import { processImage } from './utils/imgUtils.ts';
// 引入 sendData 方法
import { sendData } from './utils/sendUtils.ts';

const selectedFile = ref(null);
const imagePreview = ref('');
 
const deviceIP = ref('');

onMounted(() => {
  // 修改为使用当前URL的host作为设备IP
  deviceIP.value = window.location.hostname;
})

const bounds = reactive({
  x: 0,
  y: 0,
  w: 960,
  h: 640
});

// 选中的设备类型，默认选中第25个设备 '10.2b HD'
const selectedDeviceType = ref(24);

const w = computed(() => {
  return deviceList.fbl[selectedDeviceType.value][0];
});
const h = computed(() => {
  return deviceList.fbl[selectedDeviceType.value][1];
})
// const s = computed(() => {
//   return deviceList.fbl[selectedDeviceType.value][2];
// })

const useColorMode = computed(() => {
  return [25,37].includes(selectedDeviceType.value) 
});

watchEffect(() => {
  bounds.w = w.value;
  bounds.h = h.value;
})

// 处理文件选择
const handleFileSelect = (event: any) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target?.result as string;
      // 给 sourceBase64 赋值
      sourceBase64.value = e.target?.result as string;
      
      // 创建一个 Image 对象来获取图片的宽高
      const img = new Image();
      img.onload = () => {
        sourceWidth.value = img.width;
        sourceHeight.value = img.height;
      };
      img.src = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
};

// 处理图片拖放
const handleDrop = (event: any) => {
  event.preventDefault();
  const file = event.dataTransfer.files[0];
  if (file && file.type.startsWith('image/')) {
    selectedFile.value = file;
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target?.result as string;
      // 给 sourceBase64 赋值
      sourceBase64.value = e.target?.result as string;
      targetBase64.value = e.target?.result as string;
      // 创建一个 Image 对象来获取图片的宽高
      const img = new Image();
      img.onload = () => {
        sourceWidth.value = img.width;
        sourceHeight.value = img.height;
      };
      img.src = e.target?.result as string;
    };
    reader.readAsDataURL(file);
  }
};
const fileInput = ref<HTMLInputElement | null>(null);

const handleSelectFileClick = () => {
  fileInput.value?.click();
};

const handleDragOver = (event: any) => {
  event.preventDefault();
};

const sourceBase64 = ref('');
const sourceWidth = ref(0);
const sourceHeight = ref(0);

const targetBase64 = ref('');

// 处理灰度级别：单色
const handleGrayscaleMono = async () => {
  if (!sourceBase64.value) {
    alert('请先选择图片');
    return;
  }
  try {
    targetBase64.value = await processImage(true, false, sourceBase64.value);
  } catch (error: any) {
    console.error('处理图片失败:', error);
    alert('处理图片失败: ' + error.message);
  }
};

// 处理灰度级别：彩色
const handleGrayscaleColor = async () => {
  if (!sourceBase64.value) {
    alert('请先选择图片');
    return;
  }
  try {
    targetBase64.value = await processImage(true, true, sourceBase64.value);
  } catch (error: any) {
    console.error('处理图片失败:', error);
    alert('处理图片失败: ' + error.message);
  }
};

// 处理抖动：单色
const handleDitheringMono = async () => {
  if (!sourceBase64.value) {
    alert('请先选择图片');
    return;
  }
  try {
    targetBase64.value = await processImage(false, false, sourceBase64.value);
  } catch (error: any) {
    console.error('处理图片失败:', error);
    alert('处理图片失败: ' + error.message);
  }
};

// 处理抖动：彩色
const handleDitheringColor = async () => {
  if (!sourceBase64.value) {
    alert('请先选择图片');
    return;
  }
  try {
    targetBase64.value = await processImage(false, true, sourceBase64.value);
  } catch (error: any) {
    console.error('处理图片失败:', error);
    alert('处理图片失败: ' + error.message);
  }
};



// 上传图片
const uploadImage = async () => {
  if (!targetBase64.value) {
    alert('请先选择并处理图片');
    return;
  }
  
  try {
    console.log('上传图片到设备:', deviceIP.value);
    console.log('设备类型:', selectedDeviceType.value);
    console.log('边界设置:', bounds);
    
    // 显示上传中提示
    const loadingMessage = '上传中...';
    console.log(loadingMessage);
    
    // 调用 sendData 方法上传图片
    const result = await sendData(
      deviceIP.value,
      selectedDeviceType.value,
      bounds.w,
      bounds.h,
      targetBase64.value,
      useColorMode.value
    );
    
    if (result) {
      alert('上传成功！');
    } else {
      alert('上传失败，请检查设备连接和设置。');
    }
  } catch (error: any) {
    console.error('上传过程中发生错误:', error);
    alert('上传失败: ' + error.message);
  }
};
</script>

<template>
  <div class="container">
    <div class="content-wrapper">
      <div class="left-panel">
        <button class="btn" @click="handleSelectFileClick">选择图片文件</button>
        
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept="image/*"
          @change="handleFileSelect"
        />
        
        <button class="btn" @click="handleGrayscaleMono">灰度级别: 单色</button>
        <button class="btn" @click="handleGrayscaleColor">灰度级别: 彩色</button>
        <button class="btn" @click="handleDitheringMono">抖动处理: 单色</button>
        <button class="btn" @click="handleDitheringColor">抖动处理: 彩色</button>
        <button class="btn" @click="uploadImage">上传图片</button>
        
        <div class="input-group">
          <label>设备 IP:</label>
          <input type="text" v-model="deviceIP" />
        </div>
        
        <div class="bounds-section">
          <h3>边界设置:</h3>
          <div class="bounds-inputs">
            <div>
              <label>x:</label>
              <input type="number" v-model.number="bounds.x" />
            </div>
            <div>
              <label>y:</label>
              <input type="number" v-model.number="bounds.y" />
            </div>
            <div>
              <label>w:</label>
              <input type="number" v-model.number="bounds.w" />
            </div>
            <div>
              <label>h:</label>
              <input type="number" v-model.number="bounds.h" />
            </div>
          </div>
        </div>
        
        <div class="device-options">
          <div v-for="(name, index) in deviceList.name" :key="index" class="device-option">
            <input 
              type="radio" 
              :id="`device-${index}`" 
              :value="index" 
              v-model="selectedDeviceType"
              name="deviceType"
            />
            <label :for="`device-${index}`">{{ name }}</label>
          </div>
        </div>
      </div>
      
      <div class="right-panel">
        <h2>原始图片</h2>
        <div 
          class="drop-area" 
          @drop="handleDrop" 
          @dragover="handleDragOver"
        >
          <img v-if="imagePreview" :src="imagePreview" alt="预览" class="preview-image" />
          <div v-else class="drop-text">拖放图片到这里...</div>
        </div>
        
        <!-- 添加处理后的图片显示区域 -->
        <h2 style="margin-top: 20px">处理后图片</h2>
        <div class="processed-area">
          <img v-if="targetBase64" :src="targetBase64" alt="处理后" class="preview-image" />
          <div v-else class="drop-text">点击上方按钮处理图片...</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f0fff0;
  padding: 20px;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  display: flex;
  width: 1200px;
  gap: 30px;
}

.left-panel {
  flex: 1;
  min-width: 350px;
  max-width: 400px;
  padding: 20px;
  border-right: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background-color: #f8fdf8;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.right-panel {
  flex: 2;
  min-width: 600px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  background-color: #f8fdf8;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn {
  background-color: #e8f5e9;
  border: 1px solid #81c784;
  border-radius: 4px;
  padding: 8px 12px;
  cursor: pointer;
  text-align: center;
  margin-bottom: 6px;
  font-size: 15px;
  color: #2e7d32;
  transition: all 0.2s;
  font-weight: 500;
}

.btn:hover {
  background-color: #c8e6c9;
}

.input-group {
  margin: 10px 0;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
  color: #2e7d32;
  font-weight: bold;
  font-size: 15px;
}

.input-group input {
  width: 100%;
  padding: 6px;
  border: 1px solid #81c784;
  border-radius: 4px;
  font-size: 15px;
}

.bounds-section {
  margin: 10px 0;
}

.bounds-section h3 {
  color: #2e7d32;
  margin-bottom: 6px;
  text-align: center;
  font-size: 16px;
}

.bounds-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.bounds-inputs label {
  color: #2e7d32;
  margin-right: 5px;
  font-size: 15px;
}

.bounds-inputs input {
  width: 70px;
  padding: 4px 6px;
  border: 1px solid #81c784;
  border-radius: 4px;
  font-size: 14px;
}

.device-options {
  margin-top: 10px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  max-height: 350px;
  overflow-y: auto;
  font-size: 14px;
  padding-right: 5px;
}

.device-option {
  display: flex;
  align-items: center;
  gap: 5px;
}

.device-option label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #1a1a1a;
  font-weight: 500;
}

.device-option input[type="radio"] {
  accent-color: #2e7d32;
  width: 16px;
  height: 16px;
}

.device-option input[type="radio"]:checked + label {
  color: #2e7d32;
  font-weight: bold;
}

.processed-area {
  flex: 1;
  border: 2px dashed #81c784;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f1f8e9;
  min-height: 400px;
  margin-top: 10px;
}

.drop-text {
  color: #2e7d32;
  font-size: 24px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .content-wrapper {
    width: 100%;
  }
}

@media (max-width: 900px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .left-panel, .right-panel {
    flex: none;
    width: 100%;
    max-width: 100%;
    min-width: auto;
  }
  
  .left-panel {
    border-right: none;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 20px;
    margin-bottom: 20px;
  }
}
</style>
